package com.cy.pj.projects.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.projects.pojo.PortalProjectVO;
import com.cy.pj.projects.service.PortalProjectService;
import com.cy.pj.common.bo.PageObject;
import com.cy.pj.projects.dao.PortalProjectDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/*
 * 业务逻辑层;
 * */
@Service
public class PortalProjectServiceImpl implements PortalProjectService {
    @Autowired
    private PortalProjectDao portalProjectDao;

    //1.基于项目名,查询 项目类数据;
    @Override
    public PageObject<PortalProjectVO> getPortalProjectPageObjects(String projectName, Integer pageCurrent) {
        //1.验证pageCurrent参数的合法性;    ---  保证程序更加的健壮;
        //下面 || 两把左右别互换,首先要进行非空判断;
        if (pageCurrent == null || pageCurrent < 1) throw new IllegalArgumentException("当前输入的页码不正确");   //抛出非法参数错误;

        //2.基于用户名username条件,查询记录总数;
        int rowCount = portalProjectDao.getRowCount(projectName);
        if (rowCount == 0) throw new ServiceException("系统没有查到对应记录");   //自定义异常;

        //3.基于条件得到,当前页记录数的起始位置 和 查询当前页记录;
        //3.1定义每页显示几条数据;
        int pageSize = 12;
        //3.2返回当前页记录数的起始位置startIndex;  SQL语句中的分页查询 == limit (页码-1)*每页显示记录数, 每页显示记录数;
        int startIndex = (pageCurrent - 1) * pageSize;
        //3.3返回查询当前页记录 records ;  执行SQL语句获得;
        List<PortalProjectVO> records = portalProjectDao.getPortalProjectPageObjects(projectName, startIndex, pageSize);

        //4.对分页信息以及当前页记录进行封装;   new PageObject实例,把数据存入;
        //创建有参的对象也行的;
        PageObject<PortalProjectVO> pageObject = new PageObject<>();
        //4.1封装往对象存入页码;
        pageObject.setPageCurrent(pageCurrent);
        //4.2封装存入每页显示记录数据;
        pageObject.setPageSize(pageSize);
        //4.3封装存入查询到的记录总数;
        pageObject.setRowCount(rowCount);
        //4.4封装存入计算得到的总页数;
        int pageCount = (rowCount - 1) / pageSize + 1;
        pageObject.setPageCount(pageCount);
        //4.5封装存入当前页记录;
        pageObject.setRecords(records);

        //5.返回封装结果对象;
        //  是一个带有当前 页码值pageCurrent, 每页带有数据数pageSize, 总行数rowCount,
        //  总页数pageCount, 当前页显示数据records, 的PageObject对象;
        return pageObject;
    }
}
